package com.stylefeng.guns.modular.clm.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.aspectj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.clm.AdminConstant;
import com.stylefeng.guns.core.util.clm.AdminTools;
import com.stylefeng.guns.core.util.clm.RedisService;
import com.stylefeng.guns.modular.clm.service.IClmColumnRoomService;
import com.stylefeng.guns.modular.clm.service.IClmRoomService;
import com.stylefeng.guns.modular.clm.service.IColumnService;
import com.stylefeng.guns.modular.system.model.ClmColumnRoom;
import com.stylefeng.guns.modular.system.model.ClmRoom;
import com.stylefeng.guns.modular.system.model.Column;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-05-19 09:22:33
 */
@Controller
@RequestMapping("/column")
public class ColumnController extends BaseController {

	private final static Logger logger = LoggerFactory.getLogger(ClmRoomController.class);
    private String PREFIX = "/clm/column/";
    
    @Autowired
	private RedisService redisService ;
    
    @Autowired
    private IColumnService columnService;
    
    @Autowired
    private IClmColumnRoomService clmColumnRoomService;
    
    @Autowired
    private IClmRoomService clmRoomService;
    
    @Autowired
    private GunsProperties gunsProperties;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "column.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/column_add")
    public String columnAdd() {
        return PREFIX + "column_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/column_update/{columnId}")
    public String columnUpdate(@PathVariable Integer columnId, Model model) {
        Column column = columnService.selectById(columnId);
        model.addAttribute("item",column);
        LogObjectHolder.me().set(column);
        return PREFIX + "column_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Column column) {
    	EntityWrapper<Column> entityWrapper=new EntityWrapper<Column>();
    	Wrapper<Column> wrapper=null ;
    	logger.info("==================="+column.toString());
    	if(StringUtils.isNotBlank(column.getSiteId())){
    		wrapper=entityWrapper.eq("site_id", column.getSiteId());
    	}
    	if(StringUtils.isNotBlank(column.getColumnName())){
    		wrapper=entityWrapper.like("column_name", column.getColumnName());
    	}
    	/*if(StringUtils.isNotBlank(column.getBeDelete())){
    		wrapper=entityWrapper.eq("be_delete", column.getBeDelete());
    	}*/
    	if(StringUtils.isNotBlank(column.getBeEdit())){
    		wrapper=entityWrapper.eq("be_edit", column.getBeEdit());
    	}
    	
    	entityWrapper.eq("site_id", AdminConstant.DEFAULT_SITEID);
    	entityWrapper.eq("be_delete", "0");
    	entityWrapper.orderBy("site_id", true);
    	wrapper=entityWrapper.orderBy("num", true);
    	if(wrapper==null){
    		 return columnService.selectList(null);
    	}else{
    		List<Column> l_column = columnService.selectList(wrapper);
        	
        	return l_column;
    	}
    	
       
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Column column) {
    	String hengPicture = this.getPara("hengAvatar");
    	String shuPicture = this.getPara("shuAvatar");
    	if(StringUtils.isNotBlank(hengPicture)){
    		column.setHengImg(upImg(hengPicture));
    	}
    	if(StringUtils.isNotBlank(shuPicture)){
    		column.setShuImg(upImg(hengPicture));
    	}
    	
    	column.setSiteId(AdminConstant.DEFAULT_SITEID);
    	
        columnService.insert(column);
        return SUCCESS_TIP;
    }
    
    /**
     * 新增
     */
  /*  @RequestMapping(value = "/add")
    @ResponseBody
    public Object add() {
    	String a=this.getPara("createDate");
        //columnService.insert(column);
        return SUCCESS_TIP;
    }*/

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer columnId) {
    	Column  column=columnService.selectById(columnId);
    	if(AdminConstant.COLUMN_JP.equals(column.getColumnDesc()) || AdminConstant.COLUMN_MS.equals(column.getColumnDesc())){
    		throw new GunsException(BizExceptionEnum.NO_DELETE_COLUMN);
    	}else{
    		column.setBeDelete("1");
            columnService.updateById(column);
            //删除栏目关联的课程
            Map<String, Object> columnMap=new HashMap<String, Object>();
        	columnMap.put("column_id", columnId);
        	columnMap.put("site_id", AdminConstant.DEFAULT_SITEID);
        	clmColumnRoomService.deleteByMap(columnMap);
    	}
    	
        return SUCCESS_TIP;
    }

    /**
     * 上下架
     */
    @RequestMapping(value = "/downOrUp")
    @ResponseBody
    public Object downOrUp(@RequestParam Integer id) {
    	Column  column=columnService.selectById(id);
    	if(AdminConstant.COLUMN_JP.equals(column.getColumnDesc()) || AdminConstant.COLUMN_MS.equals(column.getColumnDesc())){
    		throw new GunsException(BizExceptionEnum.NO_UPDOWN_COLUMN);
    	}
    	
    	if("0".equals(column.getStatus())){
    		column.setStatus("1");//状态 1-开启 0-禁用
    	}else{
    		column.setStatus("0");//状态 1-开启 0-禁用
    	}
    	/*Date date_now=new Date();
    	teacherRoom.setUpdateTime(date_now);*/
    	columnService.updateById(column);
        return SUCCESS_TIP;
    }
    
    /**
     * 置顶或取消置顶
     */
    @RequestMapping(value = "/topOrNo")
    @ResponseBody
    public Object topOrNo(@RequestParam Integer id) {
    	Column  column=columnService.selectById(id);
    	if(AdminConstant.COLUMN_JP.equals(column.getColumnDesc()) || AdminConstant.COLUMN_MS.equals(column.getColumnDesc())){
    		throw new GunsException(BizExceptionEnum.NO_TOP_COLUMN);
    	}
    	if("0".equals(column.getBeTop())){
    		column.setBeTop("1");//置顶 0-否 1-是
    	}else{
    		column.setBeTop("0");//置顶 0-否 1-是
    	}
    	Date date_now=new Date();
    	column.setUpdateDate(date_now);
    	columnService.updateById(column);
        return SUCCESS_TIP;
    }

    
    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update() {
    	String columnName=this.getPara("columnName");
		String hengPicture=this.getPara("hengAvatar");
    	String shuPicture=this.getPara("shuAvatar");
    	String columnId=this.getPara("columnId");
    	Column column=columnService.selectById(columnId);
    	
    	if(StringUtils.isNotBlank(columnName)){
    		column.setColumnName(columnName);
    	}
    	//上传图片
    	if(StringUtils.isNotBlank(hengPicture)){
    		column.setHengImg(upImg(hengPicture));
    	}
    	if(StringUtils.isNotBlank(shuPicture)){
    		column.setShuImg(upImg(shuPicture));
    	}
    	
    		
        columnService.updateById(column);
        return SUCCESS_TIP;
    }
    
    
    

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{columnId}")
    @ResponseBody
    public Object detail(@PathVariable("columnId") Integer columnId) {
        return columnService.selectById(columnId);
    }
    
    /**
     * 跳转到专题课程列表
     */
    @RequestMapping("/toColumnRoomList")
    public String toColumnRoomList(Model model) {
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	String columnDesc=this.getPara("columnDesc");
    	if(AdminConstant.COLUMN_JP.equals(columnDesc)){
    		model.addAttribute("isJP",true );
    	}else{
    		model.addAttribute("isJP",false );
    	}
    	if(AdminConstant.COLUMN_MS.equals(columnDesc)){
    		model.addAttribute("isMS",true );
    	}else{
    		model.addAttribute("isMS",false );
    	}
    	model.addAttribute("columnId", columnId);
    	model.addAttribute("siteId",siteId );
    	
        return PREFIX + "column_roomlist.html";
    }
    
    /**
     * 获取专题课程列表
     */
    @RequestMapping(value = "/columnRoomList")
    @ResponseBody
    public Object columnRoomList() {
    	List<ClmRoom> l_clmRoom =null;
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	Column  column = columnService.selectById(columnId);
    	if(AdminConstant.COLUMN_JP.equals(column.getColumnDesc())){
    		//精品课程
    		EntityWrapper<ClmRoom> entityWrapper=new EntityWrapper<ClmRoom>();
        	Wrapper<ClmRoom> wrapper=null ;
    		entityWrapper.eq("site_id", AdminConstant.DEFAULT_SITEID);
        	entityWrapper.eq("be_deleted", 0);
        	wrapper=entityWrapper.orderBy("start_date", false);
        	l_clmRoom = clmRoomService.selectList(wrapper);
    	}else{
    		l_clmRoom = clmColumnRoomService.selectColumnRooms(columnId, siteId);
    	}
         
        return l_clmRoom;
    }
    
    /**
     * 跳转到新增专题课程列表
     */
    @RequestMapping("/toColumnRoomAdd")
    public String toColumnRoomAdd(Model model) {
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	model.addAttribute("columnId", columnId);
    	model.addAttribute("siteId",siteId );
        return PREFIX + "column_roomadd.html";
    }
    
    /**
     * 获取课程
     */
    @RequestMapping(value = "/getRoom")
    @ResponseBody
    public Object getRoom() {
    	//课程编号
    	String number=this.getPara("number");
    	//课程名称
    	String roomSubject=this.getPara("roomSubject");
    	//老师ID
    	String siteId=this.getPara("siteId");
    	List<ClmRoom> l_clmRoom=null;
		try {
			EntityWrapper<ClmRoom> entityWrapper=new EntityWrapper<ClmRoom>();
	    	Wrapper<ClmRoom> wrapper=null ;
	    	if(StringUtils.isNotBlank(number)){
	    		entityWrapper.eq("number_", number);
	    	}
	    	if(StringUtils.isNotBlank(roomSubject)){
	    		entityWrapper.like("subject_", roomSubject);
	    	}
	    	if(StringUtils.isNotBlank(siteId)){
	    		entityWrapper.eq("site_id", siteId);
	    	}
	    	
	    	wrapper=entityWrapper.eq("be_deleted", 0);
	        l_clmRoom = clmRoomService.selectList(wrapper);
		} catch (Exception e) {
			logger.info("getRoom "+e.getMessage());
			e.printStackTrace();
		}
		return l_clmRoom;
    }
    
    
    /**
     * 新增专题课程
     */
    @RequestMapping(value = "/addRoom")
    @ResponseBody
    public Object addRoom() {
    	String columnId=this.getPara("columnId");
    	String siteId=AdminConstant.DEFAULT_SITEID;
    	String roomId=this.getPara("roomId");
    	
    	EntityWrapper<ClmColumnRoom> entityWrapper=new EntityWrapper<ClmColumnRoom>();
    	Wrapper<ClmColumnRoom> wrapper=null ;
    	if(StringUtils.isNotBlank(siteId)){
    		wrapper=entityWrapper.eq("site_id", siteId);
    	}
    	if(StringUtils.isNotBlank(columnId)){
    		wrapper=entityWrapper.eq("column_id", columnId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		wrapper=entityWrapper.eq("room_id", roomId);
    	}
    	
    	wrapper=entityWrapper.eq("is_delete", "0");
    	int i=clmColumnRoomService.selectCount(wrapper);
    	ClmColumnRoom ccr=new ClmColumnRoom();
    	if(i>0){
    		SUCCESS_TIP.setInfo("课程已在列表中！");
    		return SUCCESS_TIP;
    	}else{
			ccr.setColumnId(columnId);
			ccr.setSiteId(siteId);
			ccr.setRoomId(roomId);
			Date date_now=new Date();
			ccr.setCreateDate(date_now);
    	}
    	
    	clmColumnRoomService.insert(ccr);
    	SUCCESS_TIP.setInfo("操作成功");
        return SUCCESS_TIP;
    }
    
    /**
     * 删除专题课程
     */
    @RequestMapping(value = "/roomDelete")
    @ResponseBody
    public Object roomDelete() {
    	String isJP=this.getPara("isJP");
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	String roomId=this.getPara("roomId");
    	if("true".equals(isJP)){
    		//精品课程
    		ClmRoom  clmRoom = clmRoomService.selectById(roomId);
            clmRoom.setBeDeleted(1);
            clmRoomService.updateById(clmRoom);
            redisService.remove("roomIndexList"+AdminConstant.DEFAULT_SITEID);
            return SUCCESS_TIP;
    	}
    	EntityWrapper<ClmColumnRoom> entityWrapper=new EntityWrapper<ClmColumnRoom>();
    	Wrapper<ClmColumnRoom> wrapper=null ;
    	if(StringUtils.isNotBlank(siteId)){
    		wrapper=entityWrapper.eq("site_id", AdminConstant.DEFAULT_SITEID);
    	}
    	if(StringUtils.isNotBlank(columnId)){
    		wrapper=entityWrapper.eq("column_id", columnId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		wrapper=entityWrapper.eq("room_id", roomId);
    	}
    	
    	wrapper=entityWrapper.eq("is_delete", "0");
    	ClmColumnRoom ccr =clmColumnRoomService.selectOne(wrapper);
    	ccr.setIsDelete("1");
    	clmColumnRoomService.updateAllColumnById(ccr);
        return SUCCESS_TIP;
    }
    
    /**
     * 置顶专题课程
     */
    @RequestMapping(value = "/roomTopOrNo")
    @ResponseBody
    public Object roomTopOrNo() {
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	String roomId=this.getPara("roomId");
    	
    	EntityWrapper<ClmColumnRoom> entityWrapper=new EntityWrapper<ClmColumnRoom>();
    	Wrapper<ClmColumnRoom> wrapper=null ;
    	if(StringUtils.isNotBlank(siteId)){
    		wrapper=entityWrapper.eq("site_id", siteId);
    	}
    	if(StringUtils.isNotBlank(columnId)){
    		wrapper=entityWrapper.eq("column_id", columnId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		wrapper=entityWrapper.eq("room_id", roomId);
    	}
    	
    	wrapper=entityWrapper.eq("is_delete", "0");
    	ClmColumnRoom ccr =clmColumnRoomService.selectOne(wrapper);
    	
    	if("0".equals(ccr.getBeTop())){
    		Date date_now=new Date();
        	ccr.setTopDate(date_now);
    		ccr.setBeTop("1");
    	}else{
    		ccr.setBeTop("0");
    	}
    	
    	clmColumnRoomService.updateAllColumnById(ccr);
        return SUCCESS_TIP;
    }
    
    /**
     * 置顶专题课程
     */
    @RequestMapping(value = "/roomDownOrUp")
    @ResponseBody
    public Object roomDownOrUp() {
    	String columnId=this.getPara("columnId");
    	String siteId=this.getPara("siteId");
    	String roomId=this.getPara("roomId");
    	
    	EntityWrapper<ClmColumnRoom> entityWrapper=new EntityWrapper<ClmColumnRoom>();
    	Wrapper<ClmColumnRoom> wrapper=null ;
    	if(StringUtils.isNotBlank(siteId)){
    		wrapper=entityWrapper.eq("site_id", siteId);
    	}
    	if(StringUtils.isNotBlank(columnId)){
    		wrapper=entityWrapper.eq("column_id", columnId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		wrapper=entityWrapper.eq("room_id", roomId);
    	}
    	
    	wrapper=entityWrapper.eq("is_delete", "0");
    	ClmColumnRoom ccr =clmColumnRoomService.selectOne(wrapper);
    	
    	if("0".equals(ccr.getStatus())){
    		ccr.setStatus("1");
    	}else{
    		ccr.setStatus("0");
    	}
    	
    	clmColumnRoomService.updateAllColumnById(ccr);
        return SUCCESS_TIP;
    }

    //图片上传修改
    private String upImg(String img){
    	String realPath="";
    	try {
    		//在本地保存上传的图片
        	String adminHUploadUrl = gunsProperties.getFileUploadPath() + img;
    		File fromHFile=new File(adminHUploadUrl);
        	File toHFile=new File(gunsProperties.getFileAdminUploadPath()+img);
        	FileUtil.copyFile(fromHFile, toHFile);
        	
        	//掉接口上传图片
        	String uploadUrl = "_tmp/" + img;
    		String responJson=AdminTools.updateImageUrl("admin", uploadUrl,AdminConstant.DEFAULT_SITEID);
    		logger.info("update img="+responJson);
    		if(StringUtils.isNotBlank(responJson)){
    			JSONObject jsonObj=JSON.parseObject(responJson);
    			if(!"0".equals(jsonObj.getString("result"))){
    				realPath=jsonObj.getString("realPath");
    				
    			}
    			
    		}
		} catch (Exception e) {
			e.printStackTrace();
			return realPath;
		}
    	
    	return realPath;
    }

}
